package com.thoughtworks.studentManagement.service;

import com.thoughtworks.studentManagement.model.Student;
import com.thoughtworks.studentManagement.exception.*;
import com.thoughtworks.studentManagement.repository.StudentRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public
class StudentService {

    private final StudentRepository repository;

    public StudentService(StudentRepository repository) {
        this.repository = repository;
    }

    // 功能1：获取全部学生信息
    public List<Student> getAllStudents() {
        return repository.findAll();
    }

    // 功能2：获取某个学生信息
    public Student getOneStudent(String studentNumber) {
        return repository.findById(studentNumber)
                .orElseThrow(() -> new StudentNotFoundException(studentNumber));
    }

    // 功能3：增加一名学生
    public Student createNewStudent(Student newStudent) {
        return repository.save(newStudent);
    }

    // 功能4：修改某个学生信息
    public Student updateStudentInformation(Student newStudent, String studentNumber) {
        return repository.findById(studentNumber)
                .map(student -> {
                    student.setName(newStudent.getName());
                    student.setBirthday(newStudent.getBirthday());
                    student.setGender(newStudent.getGender());
                    return repository.save(student);
                })
                .orElseThrow(() ->
                        new StudentNotFoundException(studentNumber));
    }

    // 功能5：删除某个学生
    public void deleteOneStudent(String studentNumber) {
        repository.deleteById(studentNumber);
    }

    // 附加：根据studentNumber修改某个学生姓名
    public Integer partialUpdateStudentName(String newStudentName, String studentNumber) {
        return repository.findById(studentNumber)
                .map(student -> {
                    student.setName(newStudentName);
                    return repository.updateNameByStudentNumber(newStudentName, studentNumber);
                })
                .orElseThrow(() ->
                        new StudentNotFoundException(studentNumber));
    }

}
